package com.errol.generic.http.impl;

import com.renjia.service.http.HttpComponent;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author zhang xiao bin
 * @version v1.0
 * @date 2020/09/28
 * @since v
 **/
public class HttpUrlConnectionComponent implements HttpComponent {
    private HttpURLConnection httpUrlConnection;

    public HttpUrlConnectionComponent() {
    }

    @Override
    public void generateHttpHeaderBuilder(String urlWithParams, HttpMethod httpMethod, int connectionTimeout, int readTimeout) throws Exception {
        httpUrlConnection = (HttpURLConnection) new URL(urlWithParams).openConnection();
        httpUrlConnection.setRequestMethod(httpMethod.name());
        httpUrlConnection.setConnectTimeout(connectionTimeout * 1000);
        httpUrlConnection.setReadTimeout(readTimeout * 1000);
    }

    @Override
    public void setRequestHeader(String key, String value) throws Exception {
        httpUrlConnection.setRequestProperty(key, value);
    }

    @Override
    public void writeRequestBody(byte[] data) throws Exception {
        httpUrlConnection.setDoOutput(true);
        httpUrlConnection.getOutputStream().write(data);
    }

    @Override
    public HttpStatus execute() throws Exception {
        httpUrlConnection.connect();
        return HttpStatus.resolve(httpUrlConnection.getResponseCode());
    }

    @Override
    public InputStream getInputStream() throws Exception {
        return httpUrlConnection.getInputStream();
    }

    @Override
    public InputStream getErrorStream() throws Exception {
        return httpUrlConnection.getErrorStream();
    }
}
